package com.major.dawn.leetCode.string;

import java.util.HashSet;
import java.util.Hashtable;

/**
 * 在字符串中删除特定的字符
 */
public class RemoveChars {


//   通过建立一个新的数组，存放不重复的元素，减少删除数组的移动操作
    public static String remove(String target, String args) {
        if (target == null || target == "" || args == null || args == "") {
            return target;
        }

        char[] targetChars = target.toCharArray();
        char[] argsChars = args.toCharArray();
        int modifyCharsLength = 0;
        char[] conTargetChars = new char[targetChars.length];

        for (int i = 0; i < targetChars.length ; i++) {
            boolean containArgs = false;
            for (int j = 0; j < argsChars.length ; j++) {
                if (targetChars[i] == argsChars[j]) {
                    containArgs = true;
                    break;
                }
            }
            if (!containArgs) {
                conTargetChars[modifyCharsLength] = targetChars[i];
                modifyCharsLength++;
            }

        }

        if (modifyCharsLength == 0) {
            target = "";
            return target;
        }


        char[] newTargetChars = new char[modifyCharsLength];

        System.arraycopy(conTargetChars, 0, newTargetChars, 0, modifyCharsLength);

        return String.copyValueOf(newTargetChars);
    }

    //    双指针保存数据，hashTable简化搜索
    public static String removeHashFind(String target, String args) {
        if (target == null || target == "" || args == null || args == "") {
            return target;
        }

        char[] targetChars = target.toCharArray();
        char[] argsChars = args.toCharArray();
        int modifyCharsLengthIndex = 0;

        HashSet<Character> argsCharsHash = new HashSet<>();
        for (int i = 0; i < argsChars.length; i++) {
            argsCharsHash.add(argsChars[i]);
        }

        for (int i = 0; i < targetChars.length; i++) {
            if (!argsCharsHash.contains(targetChars[i])) {
                if (i > modifyCharsLengthIndex) {
                    targetChars[modifyCharsLengthIndex] = targetChars[i];
                }
                modifyCharsLengthIndex++;
            }
        }
        char[] newTargetChars = new char[modifyCharsLengthIndex];

        System.arraycopy(targetChars, 0, newTargetChars, 0, modifyCharsLengthIndex);

        return String.copyValueOf(newTargetChars);
    }

    public static void main(String[] args) {
        String aeiou = remove("They are students.", "aeiou");

        System.out.println(aeiou);

        String aeiou1 = removeHashFind("They are students.", "aeiou");
        System.out.println(aeiou1);

    }
}
